<template>
    <div>
        <page-header title="欢迎使用">
            <template #content>
                <div>
                    这是头部信息
                </div>
            </template>
          
        </page-header>
        <el-row :gutter="10" style="margin: 0 10px;" >
            <el-col :lg="24"> 
                <page-main title="" style="margin: 0 0 20px 0;">
                       <div  style="margin: 0 0 10px 0;">
                           <el-button-group>
                          <el-button type="success" @click="dialogFormVisible = true">创建扫描</el-button>
                          <el-button type="primary" @click="getState" >获取状态</el-button>
                          <el-button type="primary" @click="submitRules" >传入测量标准</el-button>
                          <el-button type="primary" @click="getResult" >查看报表</el-button>
                          <el-button type="primary" @click="getModel" >查看模型</el-button>
                          <el-button type="primary" @click="getWord" >下载word</el-button>
                        
                        </el-button-group>
                      </div>
                       
                      <el-dialog title="创建任务" :visible.sync="dialogFormVisible">
                        
                        <el-form :model="ruleForm" :rules="rules" label-width="100px" ref="ruleForm">

                          <el-form-item label="套间名"  prop="project" >
                            <el-input v-model="ruleForm.project" autocomplete="off"></el-input>
                          </el-form-item>
                           <el-form-item label="房间名称"  prop="room" >
                            <el-input v-model="ruleForm.room" autocomplete="off"></el-input>
                          </el-form-item>

                          <el-form-item label="taskId"  prop="taskId">
                            <el-input v-model="ruleForm.taskId" autocomplete="off"></el-input>
                          </el-form-item>
                      
                           <!--<el-form-item label="楼房"  prop="building">
                            <el-input v-model="ruleForm.building" autocomplete="off"></el-input>
                          </el-form-item>

                         <el-form-item label="套房"  prop="suite" >
                            <el-input v-model="ruleForm.suite" autocomplete="off"></el-input>
                          </el-form-item>

                          <el-form-item label="房间"  prop="room" >
                            <el-input v-model="ruleForm.room" autocomplete="off"></el-input>
                          </el-form-item>

                         <el-form-item label="阶段"  prop="stage" >
                            <el-input v-model="ruleForm.stage" autocomplete="off"></el-input>
                          </el-form-item> -->

                        <el-form-item > 
                          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                          <el-button @click="resetForm('ruleForm')">重置</el-button>
                          <el-button @click="dialogFormVisible = false">取 消</el-button>
                        </el-form-item>
                        </el-form>
                        <div slot="footer" class="dialog-footer">
                        </div>
                      </el-dialog>
                      <!-- 导出pdf-->
                  <iframe id="exportPdf" src="localhost:8080/TableDesigner.html" width="0" height="0"></iframe>

                   <div id="print-table" class="table-container table-designer-container" :class="{'printToPdf': isPrintToPdfFlag}">
                  	<!-- <table class="table-configurable" border="0" cellspacing="0" cellpadding="0"> -->
                    <el-table
                        :data="tableData"
                        style="width: 100%;"
                         >
                        <el-table-column align = "center" label="室内测量报表" >
                         
                        <el-table-column align = "center" label="单位工程名称" >
                        <el-table-column align = "center" label="空间尺寸(mm)" >
                        <el-table-column align = "center" prop="taskId" label="房间编号"></el-table-column>
                        <el-table-column align = "center" label="推算值" ><el-table-column align = "center" prop="H" label="H"></el-table-column>
                       <el-table-column align = "center" prop="L1" label="L1" ></el-table-column><el-table-column align = "center" prop="L2" label="L2" ></el-table-column>
                       </el-table-column>
                       
                        <el-table-column align = "center" label="实测值" >
 
                        <el-table-column align = "center" label="东墙" ><el-table-column align = "center" prop="ewalls_p" label="平整度" ></el-table-column><el-table-column align = "center" prop="ewalls_c" label="垂直度" ></el-table-column></el-table-column>
                        <el-table-column align = "center" label="西墙" ><el-table-column align = "center" prop="wwalls_p" label="平整度" ></el-table-column><el-table-column align = "center" prop="wwalls_c" label="垂直度" ></el-table-column></el-table-column>
                        <el-table-column align = "center" label="北墙" ><el-table-column align = "center" prop="nwalls_p" label="平整度" ></el-table-column><el-table-column align = "center" prop="nwalls_c" label="垂直度" ></el-table-column></el-table-column>
                        <el-table-column align = "center" label="南墙" ><el-table-column align = "center" prop="swalls_p" label="平整度" ></el-table-column><el-table-column align = "center" prop="swalls_c" label="垂直度" ></el-table-column></el-table-column>
                        
                        <el-table-column align = "center" label="房顶" ><el-table-column align = "center" prop="ceiling_s" label="水平极差" ></el-table-column></el-table-column>
                        <el-table-column align = "center" label="地面" ><el-table-column align = "center" prop="floor_p" label="平整度" ></el-table-column></el-table-column>
                       
                        <el-table-column align = "center" label="阴阳角" >
                          <el-table-column align = "center" prop="multiwalls_en"  label="东北" ></el-table-column>
                          <el-table-column align = "center" prop="multiwalls_wn"  label="西北" ></el-table-column>
                          <el-table-column align = "center" prop="multiwalls_es"  label="东南" ></el-table-column>
                          <el-table-column align = "center" prop="multiwalls_ws"  label="西南" ></el-table-column>
                        </el-table-column> 
                       
                        </el-table-column>

                        <el-table-column align = "center" label="计算值" >
                        <el-table-column align = "center" label="净高" ><el-table-column align = "center" prop="heigth_z" label="最大偏差" ></el-table-column><el-table-column align = "center" prop="heigth_j" label="极差" ></el-table-column> </el-table-column>
                        <el-table-column align = "center" label="净开间" ><el-table-column align = "center" prop="bay_z" label="最大偏差" ></el-table-column><el-table-column align = "center" prop="bay_j" label="极差" ></el-table-column> </el-table-column>
                        <el-table-column align = "center" label="净进深" ><el-table-column align = "center" prop="depth_z" label="最大偏差" ></el-table-column><el-table-column align = "center" prop="depth_j" label="极差" ></el-table-column> </el-table-column>
                        </el-table-column>

                        </el-table-column>
                        </el-table-column>
                        
                        <el-table-column align = "center" label="验收部位" >

                        <el-table-column align = "center" label="门窗尺寸(mm)" >
                        <el-table-column align = "center" label="门窗编号" ></el-table-column>
                        <el-table-column align = "center" label="推算值" > <el-table-column align = "center" label="高度" ></el-table-column> <el-table-column align = "center" label="宽度" ></el-table-column></el-table-column>
                        <el-table-column align = "center" label="实测值" > <el-table-column align = "center" label="高度" ></el-table-column> <el-table-column align = "center" label="宽度" ></el-table-column></el-table-column>
                        <el-table-column align = "center" label="计算值" > <el-table-column align = "center" label="高度" ></el-table-column> <el-table-column align = "center" label="宽度" ></el-table-column></el-table-column>                      
                        </el-table-column>
                        </el-table-column>
  
                        </el-table-column>
                      </el-table>
                   
                      <!-- </table> -->
                     </div>

                </page-main>          
            </el-col>
        </el-row>
    </div>
</template>

<script>

import msApi from "@/api/msApi";
import axios from 'axios';

    // 导出函数
export function exportFileByInerHTML(inerHTML, typeName) {
  const dateTime = new Date();
      const dateTimeStr =
        dateTime.getFullYear() +
        "-" +
        dateTime.getMonth() +
        "-" +
        dateTime.getDay();
      let blob;
      try {
        //word文档为msword,docx为vnd,pdf文档为pdf,msexcel 为excel
        blob = new Blob([inerHTML], {
          type: "application/file"
        });
      } catch (e) {
        if (typeof console !== "undefined") {
          this.$message.error("导出失败");
          console.log(e);
        }
      }
      let objectUrl = URL.createObjectURL(blob);
      let link = document.createElement("a");
      let fname = `表格_${dateTimeStr}.${typeName}`; //下载文件的名字
      link.href = objectUrl;
      link.setAttribute("download", fname);
      document.body.appendChild(link);
      link.click();
}

  export default {
    name: "test",
    data() {
      return {    
        tableData: [], 
        loading:false,
         dialogFormVisible: false,
            ruleForm: {
                taskId: '',             
          },
            rules: {
                   taskId: [
                  { required: true, message: '请输入!', trigger: 'blur' },
                  { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
                ], project: [
                  { required: true, message: '请输入!', trigger: 'blur' },
                  { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
                ], room: [
                  { required: true, message: '请输入!', trigger: 'blur' },
                  { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
                ]
          
        }
      }
    },
   		created() {
       },
    
    mounted() {
        // this.getResult();
        // this.loading = false;

    },
    methods:{
     submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
              try {
              msApi.scan(this.ruleForm)
              this.$message.info('开始扫描'+this.ruleForm.taskId)
              this.dialogFormVisible = false    
            }catch (err) {
              console.log(err);
              this.$message.error('网络异常')
           }
          } else {
            return false;
          }
        });
      },
      
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },

      getState(){//获取当前状态
         this.$prompt('请输入任务Id', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(async({ value }) => {
              try {
              const res = await msApi.queryState(value)
              this.$message({
                showClose: true,
                dangerouslyUseHTMLString: true,
                message: '<strong>任务Id：</strong>'+res.data.data.taskId
                +'</br></br><strong>状态 ：</strong>'+res.data.data.state
                +'</br></br><strong>进度 ：</strong>'+res.data.data.progress+'%'
              });
            }catch (err) {
              console.log(err);
              this.$message.error('网络异常')
             }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
    },

          submitRules(){//上传测量标准
         this.$prompt('请输入任务Id', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(async({ value }) => {
              try {
              const res = await msApi.submitRules(value)
              this.$message.success("传入成功");
            }catch (err) {
              console.log(err);
              this.$message.error('网络异常')
             }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
    },

    async getResult(){//获取报表
           this.loading = true;
              try {
              const res = await msApi.getResult()
              // this.total = res.body.count;
              // this.currentPage = res.body.curr;
              var arr = new Array(3);
              // console.log(res.data);
              console.log(res.data.data);
              let _walls = res.data.data.walls;
              let wall_info = res.data.data.wall_info;
              let ewalls_p = '无',swalls_p = '无',wwalls_p = '无',nwalls_p = '无';
              let ewalls_c = '无',swalls_c = '无',wwalls_c = '无',nwalls_c = '无';
              let ceiling_s = '无',floor_p = '无';
              let bay_z = '无',bay_j = '无',depth_z = '无',depth_j = '无',heigth_z= '无',heigth_j = '无';
              let multiwalls_en = '无',multiwalls_wn = '无',multiwalls_es = '无',multiwalls_ws = '无'
        
              // let eastWall,southWall,westWall,northWall;
              //仅考虑一个方向只有一堵墙的方正毛坯房的情况
              if(Object.keys(res.data.data.wall_info).length>4){
                this.$message.error('测量数据有问题，超过4堵墙了');
                return;
              }
              let wall_map = new Map();
              for(const i in wall_info){
                switch(wall_info[i]){
                  case 'E':
                    wall_map.set("E",i);
                    if(_walls[i]==undefined){
                      continue;
                    }
                    const eastWall = _walls[i].measurements;
                    for(const key in eastWall){
                      switch(eastWall[key].id){
                        case "2":
                          ewalls_p = eastWall[key].value;
                          break;
                        case "3":
                          ewalls_c = eastWall[key].value;
                          break;
                      }
                    }
                    break;
                  case 'S':
                    wall_map.set("S",i)
                    if(_walls[i]==undefined){
                      continue;
                    }
                    const southWall = _walls[i].measurements;
                    for(const key in southWall){
                      switch(southWall[key].id){
                        case "2":
                          swalls_p = southWall[key].value;
                          break;
                        case "3":
                          swalls_c = southWall[key].value;
                          break;
                      }
                    }
                    break;
                  case 'W':
                    wall_map.set("W",i);
                    if(_walls[i]==undefined){
                      continue;
                    }
                    const westWall = _walls[i].measurements;
                    for(const key in westWall){
                      switch(westWall[key].id){
                        case "2":
                          wwalls_p = westWall[key].value;
                          break;
                        case "3":
                          wwalls_c = westWall[key].value;
                          break;
                      }
                    }
                    break;
                  case 'N':
                    wall_map.set("N",i);
                    if(_walls[i]==undefined){
                      continue;
                    }
                    const northWall = _walls[i].measurements;break;
                    break;
                }
              }
              // console.log(wall_map);
              // console.log(wall_info);
              // console.log(res.data.data.wall_info.length);
              // console.log(Object.keys(res.data.data.wall_info))

              //处理天花板水平极差数据
              // console.log(res.data.data.room.measurements)
              const ceiling_info = res.data.data.ceiling.measurements;
              for(let i in ceiling_info){
                if(ceiling_info[i].id=="4"){
                  ceiling_s = ceiling_info[i].value;  //这是一个array
                  const _ceilingMax = Math.max(...ceiling_s);
                  const _ceilingMin = Math.min(...ceiling_s);
                  ceiling_s = _ceilingMax - _ceilingMin;
                }
              }
              //处理地板平整度数据
              const floor_info = res.data.data.floor.measurements;
              for(let i in floor_info){
                if(floor_info[i].id=="4"){
                  floor_p = floor_info[i].value; 
                }
              }
              //处理阴阳角数据
              const multiwalls_info = res.data.data.multiwalls;
              
              const room_info = res.data.data.room.measurements;
              for(let i in room_info){
                //id=21,净开间、净深最大值最小值
                if(room_info[i].id=="21"){
                  let bay_depth_arr = room_info[i].value;
                  //防止没测出数据，最大最小都为0的情况
                  if(bay_depth_arr[1]!=0 && bay_depth_arr[0]!=0){
                    //净开间极差
                    bay_j = bay_depth_arr[1]-bay_depth_arr[0];
                    // console.log(bay_j)
                  }
                  if(bay_depth_arr[3]!=0 && bay_depth_arr[2]!=0){
                    //净深极差
                    depth_j = bay_depth_arr[3]-bay_depth_arr[2];
                    // console.log(depth_j)
                  }
                }
                //id=8,净开间偏差
                if(room_info[i].id=="8"){
                  const bay_z_arr = room_info[i].value;
                  bay_z = bay_z_arr;
                }
                //id=8,净深偏差
                if(room_info[i].id=="9"){
                  const depth_z_arr = room_info[i].value;
                  depth_z = depth_z_arr;
                }
                //id=6,净高偏差
                if(room_info[i].id=="6"){
                  const heigth_arr = room_info[i].value;
                  heigth_z = heigth_arr;
                }
              }

              for(var i=0;i<3;i++){        
                  arr[i] = new Array(40);
                for(var j=0;j<40;j++){
                    
                    arr[i]['H'] = 1;
                    arr[i]['L1'] = 1; 
                    arr[i]['L2'] = 1
                    arr[i]['taskId'] = 1;
                    arr[i]['ewalls_p'] = ewalls_p;
                    arr[i]['ewalls_c'] = ewalls_c;
                    arr[i]['wwalls_p'] = wwalls_p;
                    arr[i]['wwalls_c'] = wwalls_c;
                    arr[i]['nwalls_p'] = nwalls_p;
                    arr[i]['nwalls_c'] = nwalls_c;
                    arr[i]['swalls_p'] = swalls_p;
                    arr[i]['swalls_c'] = swalls_c;
                    // arr[i]['ceiling_s'] = ceiling_s;
                    // arr[i]['floor_p'] = floor_p;
                    // arr[i]['heigth_z'] = heigth_z;
                    // arr[i]['heigth_j'] = heigth_j;
                    // arr[i]['bay_z'] = bay_z;
                    // arr[i]['bay_j'] = bay_j;
                    // arr[i]['depth_z'] = depth_z;
                    // arr[i]['depth_j'] = depth_j;
                    // arr[i]['multiwalls_en'] = multiwalls_en;
                    // arr[i]['multiwalls_wn'] = multiwalls_wn;
                    // arr[i]['multiwalls_es'] = multiwalls_es;
                    // arr[i]['multiwalls_ws'] = multiwalls_ws;
                     arr[i]['ceiling_s'] = 1;
                    arr[i]['floor_p'] = 1;
                    arr[i]['heigth_z'] = 1;
                    arr[i]['heigth_j'] = 1;
                    arr[i]['bay_z'] = 1;
                    arr[i]['bay_j'] = 1;
                    arr[i]['depth_z'] = 1;
                    arr[i]['depth_j'] = 1;
                    arr[i]['multiwalls_en'] = 1;
                    arr[i]['multiwalls_wn'] = 1;
                    arr[i]['multiwalls_es'] = 1;
                    arr[i]['multiwalls_ws'] = 1;
                }
            }    
              this.tableData = arr;
             

            }catch (err) {
              console.log(err);
              this.$message.error('网络异常')
             }
           this.loading = false;

          },

      getWord(){//获取扫描模型
           // 设置边框
                this.setTableStyle()
                // 变换结点，让空格
                // #print-table是我自己的外层id
                let _table_body = document.querySelector("#print-table .el-table__body-wrapper .el-table__body tbody");
                let _docHtml = document.querySelector("#print-table .el-table__header-wrapper .el-table__header");
                _docHtml.appendChild(_table_body);
                let _header_wrapper = document.querySelector("#print-table  .el-table__header-wrapper");
                exportFileByInerHTML(_header_wrapper.innerHTML, "xls"); //导出表格就用‘’xlsx/xls之类的

                // 导出完毕要把dom界面复原,然后再去除修改的格式
                let _table__body = document.querySelector("#print-table .el-table__body-wrapper .el-table__body")
                _table__body.appendChild(_docHtml.querySelector('tbody'));
                this.clearTableStyle();


              //  layui.use(['FileSaver','wordexport'], function () {
              //  var table = layui.table,
              //  wordexport = layui.wordexport
              //      $("#content").wordExport("报表")
              //  })

              // this.setTableStyle();
              // let iframe = document.getElementById("exportPdf");
              // let doc = iframe.contentWindow.document;
              // // #print-table是自己的外层id
              // let tcontent = document.querySelector("#print-table .el-table").innerHTML; //获取table表中数据

              // //将获取到html标签数据赋值给iframe中组件中id中，组件的样式将影响html标签数据
              // doc.getElementsByTagName("body")[0].innerHTML = tcontent; 

              // iframe.contentWindow.print(); //调取iframe打印，数据过多打印会自动分页

              // //清除样式
              // this.clearTableStyle();

      }, 

      // todo设置表格样式
    setTableStyle() {
      let tableDomList = document
        .querySelector(".table-designer-container")
        .getElementsByTagName("table");

      // 去除element的覆盖层
      this.isPrintToPdfFlag = true;
      let headRightTh = tableDomList[0]
        .getElementsByTagName("tr")[0]
        .getElementsByTagName("th");
      // 添加表头最右侧的边框
      headRightTh[headRightTh.length - 2].style.borderRight =
        "1px solid #ABABAB";

      // 遍历两个table
      let tableLength = tableDomList.length;
      for (let i = 0; i < tableLength; i++) {
        tableDomList[i].setAttribute("border", "1");
        // tableDomList[i].style.border = "#ffffff";
        let childTr = tableDomList[i].getElementsByTagName("tr");
        let childTrLength = childTr.length;
        // 第一个table是头部，没有td会报错
        if (i > 0) {
          for (let j = 0; j < childTrLength; j++) {
            let childTd = childTr[j].getElementsByTagName("td");
            let childTdLength = childTd.length;
            // 修改最后一个的边框值
            // if (childTd[childTdLength - 1].style) {
            //   childTd[childTdLength - 1].style.borderRight =
            //     "1px solid #ABABAB";
            // }

            for (let k = 0; k < childTdLength; k++) {
              // childTd[k].style.padding = "8px 0"; //改变之后与element高度一致
              // childTd[k].style.valign = "center";
              // childTd[k].style.align = "center";
              // childTd[k].style.textAlign = "center";

              // if (j == childTrLength - 1) {
              //   childTd[k].style.borderBottom = "1px solid #ABABAB";
              // }
            }
          }
        } else {
          // 去除第一个table去除最右侧的空白th
          let childTr = tableDomList[i].getElementsByTagName("tr");
          let childTrLength = childTr.length;
          for (let i = 0; i < childTrLength; i++) {
            let lastTh = childTr[i].querySelector(".gutter");
            if (lastTh) {
              lastTh.parentNode.removeChild(lastTh);
            }
          }
        }
      }
    },
 // todo清除表格样式
    clearTableStyle() {
      let tableDomList = document
        .querySelector(".table-designer-container")
        .getElementsByTagName("table");

      // 去除第一个table表头最右侧的边框
      let headRightTh = tableDomList[0]
        .getElementsByTagName("tr")[0]
        .getElementsByTagName("th");
      // headRightTh[headRightTh.length - 2].style.borderRight = "none";

      //去除右侧和最底部的样式
      for (let i = 0; i < tableDomList.length; i++) {
        tableDomList[i].setAttribute("border", "0");
        // tableDomList[i].style.border = "none";
        let childTr = tableDomList[i].getElementsByTagName("tr");
        let childTrLength = childTr.length;
        // 第一个table是头部，没有td会报错
        if (i > 0) {
          for (let j = 0; j < childTrLength; j++) {
            let childTd = childTr[j].getElementsByTagName("td");
            let childTdLength = childTd.length;
            // 修改最后一个的边框值
            // if (childTd[childTdLength - 1].style) {
            //   childTd[childTdLength - 1].style.borderRight =
            //     "none";
            // }
            // for (let k = 0; k < childTdLength; k++) {
            //   if (j == childTrLength - 1) {
            //     childTd[k].style.borderBottom = "none";
            //   }
            // }
          }
        }
      }
    },


        getModel(){//获取扫描模型
         this.$prompt('请输入任务Id', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
           window.open("http://10.7.5.131/#/h5/3dviewer?taskId="+value); 
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
      }, 
    }
  }
</script>